<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\wh\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\wh\model\Material as MaterialModel;
use app\wh\model\MaterialAinp as MaterialAinpModel;
use app\wh\model\Supplier as SupplierModel;
use app\wh\model\StockType as StockTypeModel;
use app\wh\model\MaterialGoods as MaterialGoodsModel;
use app\wh\model\Stock as StockModel;
use app\mill\model\Order as OrderModel;
use app\mill\model\Archives as ArchivesModel;
use app\wh\model\Color as ColorModel;
use form\complexTable\Builder;
use think\Db;
use think\facade\Env;

/**
 * 预采购单控制器
 * @package app\admin\controller
 */
class Materialainp extends Admin
{

    /**
     * 预采购单列表
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $type_pid = 4;
        // 获取查询条件
        $map = $this->getMap();
        // 数据列表
        $data_list = Db::name('wh_material_ainp')
            ->alias('m')
            ->field('m.*,s.title as supplier_name,u.nickname,t.title as type_name')
            ->leftJoin('wh_supplier s','m.supplier_id=s.id')
            ->leftJoin('admin_user u','m.uid=u.id')
            ->leftJoin('wh_stock_type t','m.type_pid=t.id')
            //->leftJoin('wh_material wm','m.material_sn=wm.material_sn')
            ->where($map)
            ->order('m.id desc')
            ->paginate()
            ->each(function ($v){

                $html = '<tr class="new-title-w"><td colspan="7" style="height: 10px;padding: unset;"></td></tr>';
                $html .= '<tr class="new-title"><td colspan="7" style="background-color: #edf6fd;font-weight: 600;">';

                $html .= '<div style="float: left">
                        <label class="css-input css-checkbox css-checkbox-primary"><input class="ids" type="checkbox" name="ids[]" value="'.$v['id'].'"><span></span></label>
                        预采购单号：'.$v['ainp_sn'].'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;创建人：'.$v['nickname'].'</div>';
                $html .= '<div style="float: right;margin-right: 40px"><a style="color: #3152ef;" href="'.url('add', [ 'id' => $v['id']]).'">预采购单详情</a></div>';

                $html .= '</td></tr>';

                $v['title'] = $html;

                return $v;
            })
        ;

        //JS
        $js = '<script type="text/javascript">
                $(function(){
                    $(".hidden-remove").remove();
                });
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('铝卷预采购单') // 页面标题
            ->setTableName('wh_material_ainp') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                //['select:1', 'm.status', '采购状态', 'eq','',MaterialModel::$status],
                //['select:2', 'm.supplier_id', '供应商', 'eq','',SupplierModel::getGroup()],
                //['select:1', 'm.type_pid', '采购类型', 'eq','',StockTypeModel::getGroup()],
                //['text:2', 'm.material_sn', '采购单号', 'like'],
                //['daterange:2', 'm.create_time', '采购日期'],
            ])
            ->addTrClass('hidden-remove','title','<>','')
            ->hideColumn('title','remove')
            ->addColumns([ // 批量添加列
                ['title', ''],
                ['create_time', '创建日期','date'],
                ['supplier_name', '供应商'],
                ['type_name', '采购类别'],
                ['number', '需求数量'],
                ['material_sn','关联采购单','callback',function($value, $data){
                    return $value;
                },'__data__'],
                ['note', '备注'],
                ['right_button', '操作', 'btn']
            ])
            ->setExtraJs($js)
            //->addTopButton('selectOrder',['title' => '新增采购单','href' => url('selectOrder'),'icon'=>'','class'=>'btn btn-primary'],['area' => ['780px', '40%'], 'title' => ['新增采购单', 'font-size:24px;text-align: center;']])
            ->addTopButton('ainpAdd',['title' => '新建','href' => url('add',['type_pid'=>$type_pid]),'icon'=>'','class'=>'btn btn-primary'])
            ->addTopButton('delete',['title' => '删除','href' => url('delete'),'icon'=>'','class'=>'btn bg-info-light ajax-post confirm'])
            ->addRightButton('ainpAdd', ['title' => '查看', 'href' => url('add', [ 'id' => '__id__']), 'icon' => ''])
            ->addRightButton('materialAdd', ['title' => '创建采购单', 'href' => url('wh/material/add', [ 'ainp_id' => '__id__','type_pid'=>$type_pid]), 'icon' => ''])
            //->addRightButton('showPrint',['title' => '导出','href' => url('showPrint',['id'=>'__id__','print'=>'2']),'class'=>'btn bg-info-light disable-dch','icon'=>'','target'=>'_blank'])
            //->addRightButton('showPrint',['title' => '打印','href' => url('showPrint',['id'=>'__id__','print'=>'1']),'class'=>'btn bg-info-light disable-dch','icon'=>'','target'=>'_blank'])


            ->replaceRightButton(['material_sn' => ['<>','']],'',['materialAdd'])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 300,
                'mobile'  => 80,
                'sales_mobile'  => 80,
                'address'  => 150,
                'status'  => 280,
            ])
            ->fetch(); // 渲染模板
    }

    /**
     * 新增
     * @return mixed
     */
    public function add()
    {

        $id = input('id');
        $type_pid = input('type_pid');

        if ($this->request->isPost()) {
            $data = input();

            //要校验的字段
            $validate = [
                'type_id'               =>  '请选择物料类别',
                'supplier_id'           =>  '请选择供应商',
                'quality'               =>  '请选择材质',
                'material_name'         =>  '请填写物料名称',
                'num'                   =>  '请填写需求量',
                'high'                  =>  '请填写厚度',
                'long'                  =>  '请填写长度',
                'model'                 =>  '请填写规格',
            ];
            $lists = MaterialModel::serialize($data['goods'],0,$validate);
            if(!is_array($lists))$this->error($lists);

            $data['ainp_sn'] = MaterialAinpModel::getAinpSn();//采购单编号
            if(empty($data['create_time']))$data['create_time'] = date('Y-m-d H:i:s');
            $data['create_time'] = strtotime($data['create_time']);
            if(!empty($data['address_time']))$data['address_time'] = strtotime($data['address_time']);
            $data['update_time'] = time();
            $data['number'] = 0;

            foreach ($lists as &$v){

                $v['long'] = sprintf ("%04d", $v['long']);
                $v['model'] = "{$v['high']}*{$v['long']}";
                $data['number'] += floatval($v['number']);
                $data['supplier_id'] = $v['supplier_id'];
            }
            $data['goods'] = json_encode($lists,JSON_UNESCAPED_UNICODE);

            if(!empty($id)){

                $info = Db::name('wh_material_ainp')->where(['id'=>$id])->find();

                $data['id'] = $id;
                if($data['status']<0)$data['status'] = 0;
                unset($data['create_time']);
                unset($data['material_sn']);
                $re = MaterialAinpModel::update($data);
            }
            else {
                $re = MaterialAinpModel::create($data);
                $data['id'] = $re['id'];
            }
            //Db::name('wh_material_ainp')->where([['id','=',$data['id']]])->update(['number'=>$data['number'],'supplier_id'=>$data['supplier_id']]);

            if($re)$this->success('操作成功', cookie('__forward__'));
            $this->error('操作失败');
        }

        //数据
        if($id){
            $info = Db::name('wh_material_ainp')->where(['id'=>$id])->find();

            $type_pid = $info['type_pid'];

            $info['lists'] = json_decode($info['goods'],true);

        }
        else{

            $info['id'] = '';
            $info['uid'] = UID;//申请人
            $info['ainp_sn'] = MaterialAinpModel::getAinpSn();//采购单编号
            $info['type_pid'] = $type_pid;//采购类别 喷涂，转印等
            $info['type_id'] = 1;//物料类型 暂时写死
            $info['number'] = 0;//采购量
            $info['note'] = '';//备注
            $info['create_time'] = time();//创建日期

            $info['lists'] = [[
                'id'                =>  '',
                'stock_sn'          =>  '',
                'material_id'       =>  '',
                'order_id'          =>  '',
                'supplier_id'       =>  '',
                'type_pid'          =>  $type_pid,
                'type_id'           =>  '',
                'material_name'     =>  '',
                'sum_number'        =>  '',
                'number'            =>  '',
                'num'               =>  1,
                'model'             =>  '',
                'model_list'        =>  [],
                'long'              =>  '',
                'high'              =>  '',
                'quality'           =>  '',
                'row_area'          =>  '',
                'row_area2'         =>  '',
                'kg'                =>  '',
                'kg2'               =>  '',
            ]];
        }
        $info['stock_type'] = StockTypeModel::getGroup($type_pid);
        $info['supplier'] = SupplierModel::getGroup(0,$type_pid);
        $info['quality'] = ColorModel::getQuality();
        $info['model_list'] = [];

        $fromItems = MaterialAinpModel::getTabFrom($type_pid,$info);

        $method = ['method'=>'post','submit'=>'提交','isAjax'=>'ajax-post'];

        //js
        $js = '<script type="text/javascript">

                $(".hidden-border-left-right").parent("td").css("border-left","hidden");
                $(".hidden-border-left-right").parent("td").css("border-right","hidden");
                
                $(".td-bg-color").parent("td").addClass("td-bg-color");
                $.each($(".td-width"),function(i) {
                    var width = $(this).data("width");
                    $(this).parents("td").css("width",width);
                });
                
                //禁用输入框
                var type_pid = '.$type_pid.';
                $("input[name=\'goods[sum_number][]\']").attr("placeholder","自动获取库存");
                $("input[name=\'goods[sum_number][]\']").attr("disabled","disabled");
                
                //删除
                function goods_del(obj) {
                    var length = $(".goods_del").parent("td").parent("tr").length;
                    
                    if(length == 1){
                        return false;
                    }
                    $(obj).parent().parent().remove();
                }
                //新增
                function goods_add(obj) {
                    var add = $(".goods").parent().parent().html();
                    add = "<tr class=\'hidden\'>"+add+"</tr>";
                    $(add).insertAfter($(".goods").parent("td").parent("tr:last"));
                    $(".goods").parent("td").parent("tr:last").find("span.select2").remove();
                    $(".goods").parent("td").parent("tr:last").removeClass("hidden");
                    $(".goods").parent("td").parent("tr:last").find("input[name=\'goods[id][]\']").val("");
                    
                    App.initHelpers(["select2"]);
                }
                //长宽点击事件
                $("body").on("keyup","input[name=\'goods[long][]\'],input[name=\'goods[high][]\']",function(){
                    var tr_obj = $(this).parents("tr");
                    var long = tr_obj.find("input[name=\'goods[long][]\']").val();
                    var high = tr_obj.find("input[name=\'goods[high][]\']").val();
                    var model = high+"*"+long;
                    
                    tr_obj.find("input[name=\'goods[model][]\']").val(model);
                });
                
            </script>';

        $title = '新建预采购单';
        if($id)$title = '预采购单详情';
        return ZBuilder::make('form')
            ->setPageTitle($title) // 页面标题
            ->addHidden('uid')
            ->addHidden('order_ids')
            ->addHidden('order_color_ids')
            ->addHidden('supplier_id')
            ->addHidden('type_pid')
            ->addHidden('type_id')
            ->addHidden('row_area')
            ->addHidden('number')
            ->addHidden('status')
            ->addSelect('','仅加载select插件用','', $info['supplier'],'','','hidden')
            ->addDate('','仅加载date插件用','', '','','','hidden')
            ->addFormItems($fromItems)
            ->setFormData($info)
            ->setExtraJs($js)
            ->hideBtn(['submit', 'back'])
            ->method($method['method'])
            ->addBtn('<button type="submit" class="btn btn-radius btn-lg btn-minlg btn-primary '.$method['isAjax'].'" target-form="form-builder" >'.$method['submit'].'</button>')
            ->addBtn('<button type="button" class="btn btn-radius btn-lg btn-minlg bg-info-light" onclick="window.location.href=\''.cookie('__forward__').'\';return false;">返回</button>')
            ->layout(['note'=>12])
            ->fetch();

    }

    /**
     * 删除
     * @return mixed
     */
    public function delete($record = [])
    {

        if ($this->request->isPost()) {
            $data = $this->request->post();

            $ids = $data['ids'];

            if(empty($ids))$this->error('请选择预采购单');

            foreach ($ids as $id){
                $info = Db::name('wh_material_ainp')->where(['id'=>$id])->find();

                Db::name('wh_material_ainp')->where(['id'=>$id])->delete();
            }

            $this->success('操作成功');
        }

        $this->error('请选择预采购单');

    }

    /**
     * 导出采购单
     */
    public function showPrint(){

        $id = input('param.id');
        $print = input('print');

        $info = Db::name('wh_material')->where(['id'=>$id])->find();

        $type_pid = $info['type_pid'];

        if($type_pid == 1 || $type_pid == 2){
            $info['lists'] = Db::name('mill_order')->where([['id','in',$info['order_ids']]])->select();
            foreach ($info['lists'] as &$v){
                //总面积
                $v['row_area'] = 0;
                $where = [
                    ['g.order_id','=',$v['id']],
                    ['g.material_id','=',$info['id']],
                ];
                $v['lists'] = Db::name('wh_material_goods')
                    ->alias('g')
                    ->field('g.*,o.archives_sn,o.engineering,s.title as supplier,st.title as type_name,ct.title as color_type_name')
                    ->leftJoin('mill_order o','g.order_id=o.id')
                    ->leftJoin('wh_supplier s','g.supplier_id=s.id')
                    ->leftJoin('wh_stock_type st','g.type_id=st.id')
                    ->leftJoin('wh_supplier_color_type ct','g.color_type_id=ct.id')
                    ->where($where)
                    ->order('g.id asc')
                    ->select();
                foreach ($v['lists'] as &$vv){
                    //供应商
                    $v['supplier'] = $vv['supplier'];
                    $info['supplier_id'] = $vv['supplier_id'];
                    //总面积
                    $v['row_area'] += $vv['row_area'];
                    $info['row_area'] += $vv['row_area'];
                    //采购量
                    $info['number'] += $vv['number'];
                    //订单颜色ID
                    $info['order_color_ids'] .= ",{$vv['id']}";
                    //获取库存
                    $vv['sum_number'] = ColorModel::getSupplierColorNum($vv['color_id']);
                };
            }
        }
        else {
            $info['lists'] = Db::name('wh_material_goods')->where([['material_id','=',$info['id']]])->select();
            foreach ($info['lists'] as &$v){
                //总面积
                if(empty($v['row_area']))$v['row_area'] = 0;
                //获取库存
                $v['sum_number'] = StockModel::getSumNumber($v);
                if($v['type_pid'] == 5){
                    $v['row_area2'] = $v['row_area'];
                    //理论重量
                    $v['kg'] = $v['long']*$v['high']*$v['row_area'];
                    //实际重量
                    $v['kg2'] = $v['long']*$v['high']*$v['row_area'];
                    //材质
                    $type_text = floatval(Db::name('wh_stock_type')->where(['id'=>$v['type_id']])->value('title'));
                    $v['model_list'] = $this->getOrderArchives(['order_id'=>$v['order_id'],'thickness'=>$type_text,'re_type'=>1]);
                    foreach ($v['model_list'] as &$vv){
                        $vv['id'] = $vv['model'];
                        $vv['title'] = $vv['model'];
                        $vv['data_html'] = "data-row_area='{$vv['row_area']}'";
                    }
                }

            }
        }
        $info['stock_type'] = StockTypeModel::getGroup($type_pid);
        $info['supplier'] = SupplierModel::getGroup();
        $info['order'] = OrderModel::getList("CONCAT(engineering,' ',archives_sn,' ',batch)",['status'=>1]);
        $info['model_list'] = [];
        $info['order_color_ids'] = trim($info['order_color_ids'],',');

        $html = MaterialModel::toHtml($type_pid,$info,$print);

        if($print == 2)$html = str_replace('window.print();',"",$html);

        exit($html);
    }


}
